<template>
  <div class="content-view">
    <!-- 工具栏 -->
    <div class="tool-bar">
      <div class="view">
        <el-input placeholder="按名称关键字筛选" v-model="searchKey.words" clearable>
          <template #suffix>
            <i class="iconfont icon-sousuo"></i>
          </template>
        </el-input>
        <!-- 条件搜索 -->
        <condition-query :data="data" @search="searchDone"/>
      </div>
      <div class="view end">
        <a href="https://habo.qq.com/" style="padding:0 20px;" target="_blank">应用安全检测</a>
        <!-- <a href="https://www.virustotal.com" style="padding:0 20px;" target="_blank">应用安全检测</a> -->
        <el-button class="up-btn" type="success" :loading="loading" v-if="user.power*1 > 90">
          <i class="iconfont icon-anzhuo"></i>上传应用
          <input type="file" ref="APK_UP" @change="apkChangeFile" class="up-input"/>
        </el-button>
      </div>
    </div>
    <!-- 表格 -->
    <el-table 
      :data="appList.filter(data => !searchKey.words || data.name.toLowerCase().includes(searchKey.words.toLowerCase()))"
      border stripe
      v-loading="loading" 
      :default-sort="{prop: 'dtCreate', order: 'ascending'}"
      @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="50" align="center"/> -->
      <el-table-column label="" width="60" align="center"> 
        <template #default="scope">
          <img :src="scope.row.appicon" style="width: 32px;height: 32px;"/>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="应用名称" sortable width="180"  :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="remark" label="应用说明" sortable width="180" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="version" label="版本号" sortable width="115" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="package_name" label="包名" sortable width="180" :show-overflow-tooltip="true"> </el-table-column>
      <!-- <el-table-column prop="size" label="应用大小" sortable width="115" :show-overflow-tooltip="true"> </el-table-column> -->
      <el-table-column label="应用大小" sortable width="115" :show-overflow-tooltip="true"> 
        <template #default="scope">{{byte2mb(scope.row.size)}}</template>
      </el-table-column>
      <el-table-column prop="upload_time" label="上传时间" sortable width="200"> </el-table-column>
      <el-table-column prop="uploader_id" label="上传者" sortable width="115" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column label="操作" fixed="right" width="145" align="center">
        <template #default="scope">
          <el-button type="success" size="small" @click="handleBtn(scope.$index, scope.row, 'edit')">编辑</el-button>
          <el-button type="danger" size="small" @click="handleBtn(scope.$index, scope.row, 'del')">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <page-div ref="PAGING_COM" @change="pageChange" />
    <!-- dialog -->
    <apk-dlg ref="APK_DLG" @done="appDone"/>
    <batch-dlg ref="BATCH_DLG" @done="appDone"/>
  </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import ConditionQuery from '../fun_mod/ConditionQuery.vue'
import PageDiv from '../fun_mod/PageDiv.vue'
import http from '@/axios/http'
import util from '@/assets/js/util'
import BatchDlg from '../dialog/BatchDlg.vue'
import { ElNotification } from 'element-plus'
import ApkDlg from '../dialog/ApkDlg.vue'
import AppInfoParser from "app-info-parser"
import BMF from 'browser-md5-file';
import mqtt from '@/assets/js/mqtt'
export default {
  components: { 
    ConditionQuery,
    PageDiv,
    BatchDlg,
    ApkDlg
  },
  props:['data'],
  setup() {
    const Global = getCurrentInstance().proxy
    let user = reactive({
      id: Global.$var.user.id,
      username: Global.$var.user.username,
      power: Global.$var.user.power,
    });
    onMounted(()=>{
      sessionStorage.removeItem('aBatchData')
      getApps()
      mqttOnMsg()
    })

    function mqttOnMsg() {
      mqtt.onMsg((t,m)=>{
        loading.value = false
        let r = JSON.parse(m)
        if (r.data.returnCode == 10000) {
          let d = r.data.data
        //console.log(d)
          if (r.msgType == 90210) {
            let appFlag = sessionStorage.getItem('APP_FLAG')
            if (appFlag =='APP_LIST') {
              for (let i in d) {
                d[i].upload_time = util.formatGmt(d[i].upload_time)
                // d[i].appicon = 'https://img.51miz.com/Element/00/85/31/09/beb693ce_E853109_0e790627.png'
              }
              appList.value = d
              paging.total = r.data.count
              if (PAGING_COM.value) PAGING_COM.value.setData(paging)
            } 
          }
        }  
      })
    }

    let appList = ref([])
    let loading = ref(false)
    function getApps() {
      sessionStorage.setItem('APP_FLAG','APP_LIST')
      loading.value = true
      let msgCode = 90210
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.appid = searchKey.appid
      m.category = searchKey.category
      m.appname = searchKey.appname
      if (typeof(searchKey.status)=='number') m.status = searchKey.status
      m.vendor = searchKey.vendor
      m.version = searchKey.version
      m.package_name = searchKey.package_name
      // m.left_download_count = searchKey.left_download_count
      // m.right_down_count = searchKey.right_down_count
      m.indexPage = paging.index
      m.pageSize = paging.size
      g.message = m
    //console.log('查询所有应用：',JSON.stringify(g))
      mqtt.publish(topic,JSON.stringify(g))
    }
    // 多选
    let batchData = []
    function handleSelectionChange(e) {
      batchData = e
      sessionStorage.setItem('aBatchData',JSON.stringify(e))
    }

    // 分页
    let PAGING_COM = ref(null)
    let paging = reactive({
      total: 0,
      index: 1,
      size: 20
    })
    function pageChange(e) {
      paging.index = e
      getApps()
    }
    // 搜索
    let searchKey = reactive({
      words: '',
      appid: '',
      category: '',
      appname: '',
      status: null,
      vendor: '',
      version: '',
      package_name: '',      
      dtStart: '',
      dtEnd: '',
    })
    function searchDone(e) {
      searchKey.words = ''
      searchKey.appid = ''
      searchKey.category = ''
      searchKey.appname = ''
      searchKey.status = null
      searchKey.vendor = ''
      searchKey.version = ''
      searchKey.package_name = ''
      searchKey.dtStart = ''
      searchKey.dtEnd = ''
      e.forEach(v=>{
        if (v.t == '应用名称') searchKey.appname = v.v
        if (v.t == '版本号') searchKey.version = v.v
        if (v.t == '应用包名') searchKey.package_name = v.v
        if (v.t == '状态') searchKey.status = v.v
        if (v.t == 'dtStart') searchKey.dtStart = v.v
        if (v.t == 'dtEnd') searchKey.dtEnd = v.v
      })
      paging.index = 1
      getApps()
    }

    // 获取apk信息
    let APK_UP = ref(null)
    let APK_DLG = ref(null)
    function apkChangeFile() {
      let apk = APK_UP.value.files[0];
      let ext = apk?apk.name.substring(apk.name.length-4,apk.name.length):''
      if (ext == '.apk') {
        loading.value = true
        const parser = new AppInfoParser(apk)
        parser.parse().then(result => {
        //console.log('app info ----> ', result)
        //console.log('icon base64 ----> ', result.icon)
          const bmf = new BMF()
          bmf.md5(
            apk,(err, md5) => {
              // console.log('err:', err);
              // console.log('md5 string:', md5); // 97027eb624f85892c69c4bcec8ab0f11
              if (err) {
                ElNotification({
                  type: 'warning',
                  title: '获取md5失败，可能不是安全的安装程序',
                  message: err
                })
              } else {
                result.appicon = result.icon
                result.package_name = result.package
                result.version = result.versionName
                result.ver_order = result.versionCode
                result.md5 = md5
                result.size = apk.size
                result.flag = 'add'
                loading.value = false
                APK_DLG.value.open(apk,result)
              }
            },
            progress => {
              //console.log('progress number:', progress);
            },
          );
        }).catch(err => {
          // console.log('err ----> ', err)
          ElNotification({
            type: 'warning',
            title: '应用信息获取失败',
            message: err
          })
        })
        
      } else {
        if (!isNull(ext)) {
          ElNotification({
            type: 'warning',
            title: '应用信息获取失败',
            message: "不是有效的安卓安装程序"
          })
        } 
      }
    }
    // 编辑应用说明
    let apkInfo = ref()
    function handleBtn(index,row,f) {
      //console.log(index, row)
      let bd = JSON.parse(sessionStorage.getItem('aBatchData')) || []
      let l = bd.length
      // if (l > 0) {
      //   ElNotification({
      //     type: 'warning',
      //     title: '当前已选中'+l+'条记录',
      //     message: '选中多条数据请使用批量处理'
      //   })
      //   return
      // }
      row.flag = f
      apkInfo.value = row
      APK_DLG.value.open(null,apkInfo.value)
    }
    // 批量处理应用
    let BATCH_DLG = ref(null)
    function handleBatch() {
      let bd = JSON.parse(sessionStorage.getItem('aBatchData'))  || []
      if (batchData.length < bd.length) batchData = bd
      let e = {}
      e.flag = 'app'
      e.data = batchData
      BATCH_DLG.value.open(e)
    } 
    // 应用编辑完成
    function appDone(e) {      
      setTimeout(()=>{
        getApps()
      },1)  
    }

    function isNull(v) {
      return util.isNull(v)
    }

    function byte2mb(size) {
      size = (size / 1024) / 1024
      size = size.toFixed(1) + 'MB'
      return size
    }

    return{
      user, appList, loading, handleSelectionChange, PAGING_COM, paging, pageChange, searchKey, searchDone,
      APK_UP, APK_DLG, apkInfo, apkChangeFile, handleBtn, BATCH_DLG, handleBatch, appDone, 
      isNull, byte2mb
    }
  },
}
</script>

<style lang="scss" scoped src="./tab_content2.scss"></style>